package com.jiaxue.admin.util;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jiaxue.admin.model.Admin;
import com.jiaxue.admin.model.ReturnObj;
/**
 * 登录权限验证
 * @author donglin
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//System.out.println("---preHandle---");
		HttpSession session = request.getSession();
		Admin user = (Admin)session.getAttribute("loginUser");
		if(user==null) {
			ReturnObj obj=new ReturnObj(-1, "尚未登录", null);
			responseOutWithJson(response,obj);
			return false;
		} else {
			
		}
		return true;
	}
	
	
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		String callback = request.getParameter("callback");
		//System.out.println("---postHandle---");
	}



	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String callback = request.getParameter("callback");
			//System.out.println("---afterCompletion---");
	}



	/**
	 * 以JSON格式输出
	 * @param response
	 */
	protected void responseOutWithJson(HttpServletResponse response,
			Object responseObject) {
		//将实体对象转换为JSON Object转换
		JSONObject responseJSONObject = JSONObject.fromObject(responseObject);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
            OutputStream outs = response.getOutputStream();
            out= new PrintWriter(new OutputStreamWriter(outs,"utf-8"));
            //返回json格式的提示
            out.println(responseJSONObject.toString());
            out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}
